package cc.atliberty.oa.controller;

import cc.atliberty.oa.pojo.User;
import cc.atliberty.oa.service.UserService;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Controller;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;

@Controller
@WebServlet("/welcome")
public class WelcomeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 存储cookie的变量
        String username = null;
        String password = null;

        // 获取cookie
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                String name = cookie.getName();
                if ("username".equals(name)) {
                    username = cookie.getValue();
                } else if ("password".equals(name)){
                    password = cookie.getValue();
                }
            }
        }
        
        if (username != null && password != null){
            // 首先验证一下用户名和密码是否正确
            // 因为可能用户会改密码
            User user = new User(username,password);
            ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
            UserService userService = context.getBean("userService", UserService.class);
            User checkedUser = userService.checkUser(user);
            if (checkedUser != null){
                // 没改密码
                // 设置session
                HttpSession session = request.getSession();
                session.setAttribute("user", user);
                response.sendRedirect(request.getContextPath() + "/dept/list");
            }else {
                response.sendRedirect(request.getContextPath() + "/index.jsp");
            }
        }else {
            response.sendRedirect(request.getContextPath() + "/index.jsp");
        }
    }
}
